package com.example.backend.controller.user;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.backend.dto.request.PageUserDto;
import com.example.backend.entitly.mysql.user.Users;
import com.example.backend.enums.ResultCodeEnum;
import com.example.backend.service.mysql.user.UsersService;
import com.example.backend.utils.ResultJson;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@Tag(name = "批发商 - 用户管理", description = "仅批发商可访问的用户管理接口")
@RequestMapping("/api/wholes/user")
@RequiredArgsConstructor
@Validated
@Transactional(rollbackFor = Exception.class)
public class WholesalerController {

    private final UsersService usersService;

    public static Integer getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            return (Integer) authentication.getPrincipal();
        }
        throw new UsernameNotFoundException(ResultCodeEnum.NOT_LOGIN.getMessage());
    }

    @PreAuthorize("hasAuthority('wholes:list')")
    @PostMapping("/list")
    public ResultJson<?> listAllUsers(PageUserDto pageUserDto) {
        Integer userId = getUser();
        pageUserDto.setUserId(userId);
        Page<Users> usersPage = usersService.pageListByWholesaler(pageUserDto);
        return ResultJson.success(usersPage.getRecords());
    }

    @PreAuthorize("hasAuthority('wholes:delete-any')")
    @DeleteMapping("/user")
    public ResultJson<?> deleteUser(@PathVariable Long userId) {
        Boolean success = usersService.removeByWholesId(userId);
        if (!success) {
            return ResultJson.fail(ResultCodeEnum.USER_DELETE_FAIL.getCode(), ResultCodeEnum.USER_DELETE_FAIL.getMessage());
        }
        return ResultJson.success("删除成功");
    }

    @ExceptionHandler(value = UsernameNotFoundException.class)
    public ResultJson<?> handleUsernameNotFoundException(UsernameNotFoundException e) {
        return ResultJson.fail(ResultCodeEnum.NOT_LOGIN.getCode(), e.getMessage());
    }

}
